#include "doctorprofilewidget.h"
#include "ui_doctorprofilewidget.h"
#include "../../network/networkclient.h"
#include <QMessageBox>
#include <QJsonArray>

DoctorProfileWidget::DoctorProfileWidget(const Doctor& doctor, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::DoctorProfileWidget),
    m_doctor(doctor)
{
    ui->setupUi(this);
    
    // 连接网络信号
    connect(&NetworkClient::instance(), &NetworkClient::messageReceived,
            this, &DoctorProfileWidget::onMessageReceived);
    
    // 加载科室列表
    loadDepartments();
    
    // 加载医生信息
    loadDoctorInfo();
}

DoctorProfileWidget::~DoctorProfileWidget() {
    delete ui;
}

void DoctorProfileWidget::loadDepartments() {
    // 请求科室列表
    QJsonObject request;
    NetworkClient::instance().sendRequest(MSG_GET_DEPARTMENTS, request);
}

void DoctorProfileWidget::loadDoctorInfo() {
    // 请求医生详细信息
    QJsonObject request;
    request["user_id"] = m_doctor.id;
    NetworkClient::instance().sendRequest(MSG_GET_DOCTOR_INFO, request);
}

void DoctorProfileWidget::on_saveButton_clicked() {
    // 收集表单数据
    int departmentId = ui->departmentCombo->currentData().toInt();
    QString title = ui->titleEdit->text().trimmed();
    QString specialty = ui->specialtyEdit->text().trimmed();
    QString education = ui->educationCombo->currentText();
    int experience = ui->experienceSpinBox->value();
    QString introduction = ui->introductionEdit->toPlainText().trimmed();
    QString workTime = ui->workTimeEdit->text().trimmed();
    double consultationFee = ui->consultationFeeSpinBox->value();
    int dailyLimit = ui->dailyLimitSpinBox->value();
    QString clinicType = ui->clinicTypeCombo->currentText();
    
    // 验证必填项
    if (departmentId == 0) {
        QMessageBox::warning(this, "提示", "请选择科室");
        return;
    }
    
    if (title.isEmpty() || specialty.isEmpty()) {
        QMessageBox::warning(this, "提示", "请填写职称和专长");
        return;
    }
    
    // 构建更新请求
    QJsonObject request;
    request["user_id"] = m_doctor.id;
    request["department_id"] = departmentId;
    request["title"] = title;
    request["specialty"] = specialty;
    request["education"] = education;
    request["experience"] = experience;
    request["introduction"] = introduction;
    request["work_time"] = workTime;
    request["consultation_fee"] = consultationFee;
    request["daily_patient_limit"] = dailyLimit;
    request["clinic_type"] = clinicType;
    
    NetworkClient::instance().sendRequest(MSG_UPDATE_DOCTOR_INFO, request);
    
    ui->saveButton->setEnabled(false);
    ui->saveButton->setText("保存中...");
}

void DoctorProfileWidget::on_refreshButton_clicked() {
    loadDoctorInfo();
}

void DoctorProfileWidget::onMessageReceived(MessageType type, const QJsonObject& data) {
    if (type == MSG_GET_DEPARTMENTS_RESPONSE) {
        if (data["success"].toBool()) {
            QJsonArray departments = data["departments"].toArray();
            
            ui->departmentCombo->clear();
            for (const QJsonValue& value : departments) {
                QJsonObject dept = value.toObject();
                QString name = dept["name"].toString();
                int id = dept["id"].toInt();
                ui->departmentCombo->addItem(name, id);
            }
        }
    }
    else if (type == MSG_GET_DOCTOR_INFO_RESPONSE) {
        if (data["success"].toBool()) {
            // 更新医生信息
            m_doctor.departmentId = data["department_id"].toInt();
            m_doctor.departmentName = data["department_name"].toString();
            m_doctor.title = data["title"].toString();
            m_doctor.specialty = data["specialty"].toString();
            m_doctor.education = data["education"].toString();
            m_doctor.experience = data["experience"].toInt();
            m_doctor.introduction = data["introduction"].toString();
            m_doctor.workTime = data["work_time"].toString();
            m_doctor.consultationFee = data["consultation_fee"].toDouble();
            m_doctor.dailyPatientLimit = data["daily_patient_limit"].toInt();
            
            // 显示在界面上
            ui->usernameLabel->setText(m_doctor.username);
            ui->realNameLabel->setText(m_doctor.realName);
            ui->phoneLabel->setText(m_doctor.phone);
            
            // 设置科室下拉框
            int index = ui->departmentCombo->findData(m_doctor.departmentId);
            if (index >= 0) {
                ui->departmentCombo->setCurrentIndex(index);
            }
            
            ui->titleEdit->setText(m_doctor.title);
            ui->specialtyEdit->setText(m_doctor.specialty);
            
            // 设置学历下拉框
            int eduIndex = ui->educationCombo->findText(m_doctor.education);
            if (eduIndex >= 0) {
                ui->educationCombo->setCurrentIndex(eduIndex);
            }
            
            ui->experienceSpinBox->setValue(m_doctor.experience);
            ui->introductionEdit->setPlainText(m_doctor.introduction);
            ui->workTimeEdit->setText(m_doctor.workTime);
            ui->consultationFeeSpinBox->setValue(m_doctor.consultationFee);
            ui->dailyLimitSpinBox->setValue(m_doctor.dailyPatientLimit);
            
            // 设置门诊类型
            int clinicIndex = ui->clinicTypeCombo->findText(m_doctor.clinicType);
            if (clinicIndex >= 0) {
                ui->clinicTypeCombo->setCurrentIndex(clinicIndex);
            }
        }
    }
    else if (type == MSG_UPDATE_DOCTOR_INFO_RESPONSE) {
        ui->saveButton->setEnabled(true);
        ui->saveButton->setText("保存信息");
        
        if (data["success"].toBool()) {
            QMessageBox::information(this, "成功", "医生信息更新成功！");
            loadDoctorInfo(); // 重新加载信息
        } else {
            QMessageBox::warning(this, "失败", data["message"].toString());
        }
    }
}

